//
//  HomeViewController.m
//  SnapCAD
//
//  Created by Developer on 2025/7/25.
//

#import "HomeViewController.h"
#import "UnitConverterViewController.h"
#import "HistoryViewController.h"
#import "RukouViewController.h"
#import "Masonry.h"
#import "SVProgressHUD.h"
#import "Snmodel.h"
#import "SnToolManager.h"
#import "SnDataSourceTool.h"
#import "ProfileViewController.h"
@interface HomeViewController ()<UIDocumentPickerDelegate>

// Header Views
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UIButton *settingsButton;

// Main Content
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

// CAD Viewer Card
@property (nonatomic, strong) UIView *cadViewerCard;
@property (nonatomic, strong) UIImageView *cadImageView;
@property (nonatomic, strong) UIButton *openFileButton;
@property (nonatomic, strong) UIButton *historyButton;

// Tools Grid
@property (nonatomic, strong) UIView *toolsGridView;
@property (nonatomic, strong) UIView *converterCard;
@property (nonatomic, strong) UIView *measurementCard;

// Recent Files
@property (nonatomic, strong) UIView *recentFilesCard;

// Bottom Navigation
@property (nonatomic, strong) UIView *bottomNavView;
@property (nonatomic, strong) NSArray<UIButton *> *navButtons;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupUI];
    [self setupConstraints];
    [self loadRecentFiles];
}

// 添加导航栏设置方法
- (void)setupNavigationBar {
    // 隐藏系统导航栏，因为我们使用自定义header
    [self.navigationController setNavigationBarHidden:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupNavigationBar]; // 添加导航栏设置
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}
- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    
    [self setupHeader];
    [self setupScrollView];
    [self setupCADViewerCard];
    [self setupToolsGrid];
    [self setupRecentFilesCard];
    [self setupBottomNavigation];
}


#pragma mark - Setup Header

- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    
    // 设置纯色背景 - 使用应用的主题蓝色
    self.headerView.backgroundColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    
    self.headerView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.headerView.layer.shadowOffset = CGSizeMake(0, 2);
    self.headerView.layer.shadowOpacity = 0.15;
    self.headerView.layer.shadowRadius = 8;
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    // Title Label - 改为白色
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"SnapCAD";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];
    
    // Subtitle Label - 改为半透明白色
    self.subtitleLabel = [[UILabel alloc] init];
    self.subtitleLabel.text = @"Professional Tools";
    self.subtitleLabel.font = [UIFont systemFontOfSize:14];
    self.subtitleLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    self.subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.subtitleLabel];
    
    // Settings Button - 调整为白色主题
    self.settingsButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.settingsButton setImage:[UIImage systemImageNamed:@"gearshape.fill"] forState:UIControlStateNormal];
    self.settingsButton.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    self.settingsButton.backgroundColor = [UIColor whiteColor];
    self.settingsButton.layer.cornerRadius = 20;
    self.settingsButton.layer.shadowColor = [UIColor blackColor].CGColor;
    self.settingsButton.layer.shadowOffset = CGSizeMake(0, 2);
    self.settingsButton.layer.shadowOpacity = 0.1;
    self.settingsButton.layer.shadowRadius = 4;
    [self.settingsButton addTarget:self action:@selector(settingsButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.settingsButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.settingsButton];
}

// 添加viewDidLayoutSubviews方法来更新渐变层的frame
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    // 更新渐变层的frame
//    for (CALayer *layer in self.headerView.layer.sublayers) {
//        if ([layer isKindOfClass:[CAGradientLayer class]]) {
//            layer.frame = self.headerView.bounds;
//            break;
//        }
//    }
}

- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];
    
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
}

#pragma mark - Setup CAD Viewer Card

- (void)setupCADViewerCard {
    self.cadViewerCard = [self createCardView];
    [self.contentView addSubview:self.cadViewerCard];
    
    // Icon and Title Container
    UIView *headerContainer = [[UIView alloc] init];
    headerContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cadViewerCard addSubview:headerContainer];
    
    // Icon View
    UIView *iconView = [[UIView alloc] init];
    iconView.backgroundColor = [UIColor colorWithRed:0.93 green:0.94 blue:1.0 alpha:1.0];
    iconView.layer.cornerRadius = 12;
    iconView.translatesAutoresizingMaskIntoConstraints = NO;
    [headerContainer addSubview:iconView];
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage systemImageNamed:@"cube.fill"];
    iconImageView.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    iconImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [iconView addSubview:iconImageView];
    
    // Title and Subtitle
    UIView *textContainer = [[UIView alloc] init];
    textContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [headerContainer addSubview:textContainer];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"CAD Viewer";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.13 alpha:1.0];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [textContainer addSubview:titleLabel];
    
    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = @"View & analyze CAD files";
    descLabel.font = [UIFont systemFontOfSize:14];
    descLabel.textColor = [UIColor colorWithRed:0.42 green:0.45 blue:0.50 alpha:1.0];
    descLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [textContainer addSubview:descLabel];
    
    // CAD Image View
    self.cadImageView = [[UIImageView alloc] init];
    self.cadImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.cadImageView.clipsToBounds = YES;
    self.cadImageView.layer.cornerRadius = 12;
    self.cadImageView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    self.cadImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cadViewerCard addSubview:self.cadImageView];
    
    // Load placeholder image
    [self loadCADImage];
    
    // Buttons Container
    UIView *buttonsContainer = [[UIView alloc] init];
    buttonsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cadViewerCard addSubview:buttonsContainer];
    
    // Open File Button
    self.openFileButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.openFileButton setTitle:@"Open File" forState:UIControlStateNormal];
    [self.openFileButton setImage:[UIImage systemImageNamed:@"square.and.arrow.up"] forState:UIControlStateNormal];
    self.openFileButton.backgroundColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    [self.openFileButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.openFileButton.tintColor = [UIColor whiteColor];
    self.openFileButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.openFileButton.layer.cornerRadius = 12;
    [self.openFileButton addTarget:self action:@selector(openFileButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [buttonsContainer addSubview:self.openFileButton];
    
    // History Button
    self.historyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.historyButton setImage:[UIImage systemImageNamed:@"clock.arrow.circlepath"] forState:UIControlStateNormal];
    self.historyButton.tintColor = [UIColor colorWithRed:0.42 green:0.45 blue:0.50 alpha:1.0];
    self.historyButton.backgroundColor = [UIColor whiteColor];
    self.historyButton.layer.borderWidth = 1;
    self.historyButton.layer.borderColor = [UIColor colorWithRed:0.83 green:0.84 blue:0.86 alpha:1.0].CGColor;
    self.historyButton.layer.cornerRadius = 12;
    [self.historyButton addTarget:self action:@selector(historyButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [buttonsContainer addSubview:self.historyButton];
    
    // Setup Masonry constraints for CAD Viewer Card
    [headerContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(self.cadViewerCard);
        make.left.equalTo(self.cadViewerCard).offset(16);
        make.height.mas_equalTo(72);
    }];
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(headerContainer);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    
    
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(iconView);
        make.size.mas_equalTo(CGSizeMake(24, 24));
    }];
    
    [textContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(16);
        make.centerY.equalTo(headerContainer);
        make.right.equalTo(headerContainer);
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(textContainer);
    }];
    
    [descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(2);
        make.left.right.bottom.equalTo(textContainer);
    }];
    
    [self.cadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerContainer.mas_bottom).offset(16);
        make.left.equalTo(self.cadViewerCard).offset(16);
        make.right.equalTo(self.cadViewerCard).offset(-16);
        make.height.mas_equalTo(160);
    }];
    
    [buttonsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cadImageView.mas_bottom).offset(16);
        make.left.bottom.equalTo(self.cadViewerCard).offset(16);
        make.right.bottom.equalTo(self.cadViewerCard).offset(-16);
        make.height.mas_equalTo(48);
        make.bottom.equalTo(self.cadViewerCard.mas_bottom).offset(-16);
    }];
    
   
    
    [self.historyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(buttonsContainer);
        make.width.mas_equalTo(48);
    }];
    [self.openFileButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(buttonsContainer);
        make.right.equalTo(self.historyButton.mas_left).offset(-12);
    }];
}

#pragma mark - Setup Tools Grid

- (void)setupToolsGrid {
    self.toolsGridView = [[UIView alloc] init];
    [self.contentView addSubview:self.toolsGridView];
    
    // Unit Converter Card
    self.converterCard = [self createToolCard:@"arrow.left.arrow.right" 
                                        title:@"Unit Converter" 
                                  description:@"Convert measurements"
                                        color:[UIColor colorWithRed:0.13 green:0.69 blue:0.30 alpha:1.0]
                                   background:[UIColor colorWithRed:0.86 green:0.98 blue:0.90 alpha:1.0]
                                       action:@selector(converterButtonTapped)];
    [self.toolsGridView addSubview:self.converterCard];
    
    // Measurement Tool Card
//    self.measurementCard = [self createToolCard:@"ruler" 
//                                          title:@"Measurement" 
//                                    description:@"Precise calculations"
//                                          color:[UIColor colorWithRed:0.14 green:0.56 blue:0.88 alpha:1.0]
//                                     background:[UIColor colorWithRed:0.87 green:0.94 blue:1.0 alpha:1.0]
//                                         action:@selector(measurementButtonTapped)];
//    [self.toolsGridView addSubview:self.measurementCard];
    
    // Setup Masonry constraints for tools grid
    [self.converterCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.toolsGridView);
//        make.right.equalTo(self.measurementCard.mas_left).offset(-16);
//        make.width.equalTo(self.measurementCard);
        make.width.equalTo(@((UIScreen.mainScreen.bounds.size.width - 32)/2));
    }];
    
//    [self.measurementCard mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.top.bottom.equalTo(self.toolsGridView);
//    }];
}

#pragma mark - Setup Recent Files Card

- (void)setupRecentFilesCard {
    self.recentFilesCard = [self createCardView];
    [self.contentView addSubview:self.recentFilesCard];
    
    // 添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rukouCardTapped)];
    [self.recentFilesCard addGestureRecognizer:tapGesture];
    
    // Icon and Title Container
    UIView *headerContainer = [[UIView alloc] init];
    headerContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.recentFilesCard addSubview:headerContainer];
    
    // Icon View
    UIView *iconView = [[UIView alloc] init];
    iconView.backgroundColor = [UIColor colorWithRed:0.93 green:0.94 blue:1.0 alpha:1.0];
    iconView.layer.cornerRadius = 12;
    iconView.translatesAutoresizingMaskIntoConstraints = NO;
    [headerContainer addSubview:iconView];
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage systemImageNamed:@"photo.fill"];
    iconImageView.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    iconImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [iconView addSubview:iconImageView];
    
    // Title and Subtitle
    UIView *textContainer = [[UIView alloc] init];
    textContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [headerContainer addSubview:textContainer];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"Other Appliccations";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.13 alpha:1.0];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [textContainer addSubview:titleLabel];
    
    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = @"Entry Other Appliccations Detail";
    descLabel.font = [UIFont systemFontOfSize:14];
    descLabel.textColor = [UIColor colorWithRed:0.42 green:0.45 blue:0.50 alpha:1.0];
    descLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [textContainer addSubview:descLabel];
    
    // Arrow Icon
    UIImageView *arrowImageView = [[UIImageView alloc] init];
    arrowImageView.image = [UIImage systemImageNamed:@"chevron.right"];
    arrowImageView.tintColor = [UIColor colorWithRed:0.61 green:0.64 blue:0.69 alpha:1.0];
    arrowImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [headerContainer addSubview:arrowImageView];
    
    // Setup Masonry constraints
    [headerContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.recentFilesCard).offset(16);
        make.right.bottom.equalTo(self.recentFilesCard).offset(-16);
        make.height.mas_equalTo(72);
    }];
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(headerContainer);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(iconView);
        make.size.mas_equalTo(CGSizeMake(24, 24));
    }];
    
    [textContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(16);
        make.centerY.equalTo(headerContainer);
        make.right.equalTo(arrowImageView.mas_left).offset(-16);
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(textContainer);
    }];
    
    [descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(2);
        make.left.right.bottom.equalTo(textContainer);
    }];
    
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.centerY.equalTo(headerContainer);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    
    
    
    
}

-(void)rukouCardTapped{
    
    RukouViewController * vc = [[RukouViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

// Header
//UIView *headerView = [[UIView alloc] init];
//[self.recentFilesCard addSubview:headerView];
//
//UILabel *titleLabel = [[UILabel alloc] init];
//titleLabel.text = @"Recent Files";
//titleLabel.font = [UIFont boldSystemFontOfSize:16];
//titleLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.13 alpha:1.0];
//[headerView addSubview:titleLabel];
//
//UIButton *viewAllButton = [UIButton buttonWithType:UIButtonTypeSystem];
//[viewAllButton setTitle:@"View All" forState:UIControlStateNormal];
//viewAllButton.titleLabel.font = [UIFont systemFontOfSize:14];
//[viewAllButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//[viewAllButton setBackgroundColor:[UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0]];
//[viewAllButton addTarget:self action:@selector(viewAllFilesButtonTapped) forControlEvents:UIControlEventTouchUpInside];
//[headerView addSubview:viewAllButton];
//
//// Files List
//UIStackView *filesStackView = [[UIStackView alloc] init];
//filesStackView.axis = UILayoutConstraintAxisVertical;
//filesStackView.spacing = 12;
//[self.recentFilesCard addSubview:filesStackView];
//
//// Add file items
//NSArray *files = @[
//    @{@"name": @"floor_plan.dwg", @"time": @"2 hours ago", @"color": @"red"},
//    @{@"name": @"blueprint.dxf", @"time": @"Yesterday", @"color": @"yellow"},
//    @{@"name": @"electrical_plan.dwg", @"time": @"3 days ago", @"color": @"green"}
//];
//
//
//
//
//// Setup Masonry constraints
//[headerView mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.top.left.equalTo(self.recentFilesCard).offset(12);
//    make.right.equalTo(self.recentFilesCard).offset(-12);
//    make.height.mas_equalTo(24);
//}];
//
//[titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.centerY.equalTo(headerView);
//}];
//
//[viewAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.right.centerY.equalTo(headerView);
//}];
//
//[filesStackView mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.top.equalTo(headerView.mas_bottom).offset(16);
//    make.left.bottom.equalTo(self.recentFilesCard).offset(12);
//    make.bottom.equalTo(self.recentFilesCard).offset(-12);
//}];
//for (NSDictionary *file in files) {
//    UIView *fileItem = [self createFileItem:file];
//    fileItem.backgroundColor = [UIColor redColor];
//    [filesStackView addArrangedSubview:fileItem];
//}

#pragma mark - Setup Bottom Navigation

- (void)setupBottomNavigation {
    self.bottomNavView = [[UIView alloc] init];
//    self.bottomNavView.backgroundColor = [UIColor whiteColor];
//    self.bottomNavView.layer.borderWidth = 1;
//    self.bottomNavView.layer.borderColor = [UIColor colorWithRed:0.90 green:0.91 blue:0.93 alpha:1.0].CGColor;
    [self.contentView addSubview:self.bottomNavView];
//
//    // Navigation Buttons
//    NSArray *navItems = @[
//        @{@"icon": @"house.fill", @"title": @"Home", @"active": @YES},
//        @{@"icon": @"folder.fill", @"title": @"Files", @"active": @NO},
//        @{@"icon": @"calculator", @"title": @"Tools", @"active": @NO},
//        @{@"icon": @"gearshape.fill", @"title": @"Settings", @"active": @NO}
//    ];
//    
//    NSMutableArray *buttons = [NSMutableArray array];
//    UIStackView *stackView = [[UIStackView alloc] init];
//    stackView.axis = UILayoutConstraintAxisHorizontal;
//    stackView.distribution = UIStackViewDistributionFillEqually;
//    [self.bottomNavView addSubview:stackView];
//    
//    for (int i = 0; i < navItems.count; i++) {
//        NSDictionary *item = navItems[i];
//        UIButton *button = [self createNavButton:item[@"icon"] 
//                                           title:item[@"title"] 
//                                          active:[item[@"active"] boolValue]
//                                             tag:i];
//        [buttons addObject:button];
//        [stackView addArrangedSubview:button];
//    }
//    
//    self.navButtons = [buttons copy];
//    
//    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.bottomNavView).offset(8);
//        make.left.equalTo(self.bottomNavView).offset(24);
//        make.right.equalTo(self.bottomNavView).offset(-24);
//        make.bottom.equalTo(self.bottomNavView).offset(-8);
//    }];
}

#pragma mark - Setup Constraints

- (void)setupConstraints {
    // Header View
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(120);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headerView).offset(24);
        make.top.equalTo(self.headerView).offset(56);
    }];
    
    [self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(2);
    }];
    
    [self.settingsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView).offset(-24);
//        make.centerY.equalTo(self.headerView);
        make.top.equalTo(self.headerView).offset(60);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    // Scroll View
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
//        make.bottom.equalTo(self.bottomNavView.mas_top);
    }];
    
    // Content View
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    // CAD Viewer Card
    [self.cadViewerCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(16);
        make.left.equalTo(self.contentView).offset(16);
        make.right.equalTo(self.contentView).offset(-16);
    }];
    
    // Tools Grid
    [self.toolsGridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cadViewerCard.mas_bottom).offset(16);
        make.left.equalTo(self.contentView).offset(16);
        make.right.equalTo(self.contentView).offset(-16);
        make.height.mas_equalTo(120);
    }];
    
    // Recent Files Card
    [self.recentFilesCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.toolsGridView.mas_bottom).offset(16);
        make.left.equalTo(self.contentView).offset(16);
        make.right.equalTo(self.contentView).offset(-16);

    }];
    
    // Bottom Navigation
    [self.bottomNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.recentFilesCard.mas_bottom).offset(16);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(80);
        make.bottom.equalTo(self.contentView).offset(-16);
    }];
}

#pragma mark - Helper Methods

- (UIView *)createCardView {
    UIView *cardView = [[UIView alloc] init];
    cardView.backgroundColor = [UIColor whiteColor];
    cardView.layer.cornerRadius = 16;
    cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    cardView.layer.shadowOffset = CGSizeMake(0, 4);
    cardView.layer.shadowOpacity = 0.08;
    cardView.layer.shadowRadius = 20;
    
    // Add padding
    UIView *paddingView = [[UIView alloc] init];
    [cardView addSubview:paddingView];
    
    [paddingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cardView).insets(UIEdgeInsetsMake(20, 20, 20, 20));
    }];
    
    return cardView;
}

- (UIView *)createToolCard:(NSString *)iconName 
                     title:(NSString *)title 
               description:(NSString *)description 
                     color:(UIColor *)iconColor 
                background:(UIColor *)backgroundColor 
                    action:(SEL)action {
    UIView *cardView = [[UIView alloc] init];
    cardView.backgroundColor = [UIColor whiteColor];
    cardView.layer.cornerRadius = 16;
    cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    cardView.layer.shadowOffset = CGSizeMake(0, 4);
    cardView.layer.shadowOpacity = 0.08;
    cardView.layer.shadowRadius = 20;
    
    // Add tap gesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:action];
    [cardView addGestureRecognizer:tapGesture];
    
    // Icon View
    UIView *iconView = [[UIView alloc] init];
    iconView.backgroundColor = backgroundColor;
    iconView.layer.cornerRadius = 12;
    [cardView addSubview:iconView];
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage systemImageNamed:iconName];
    iconImageView.tintColor = iconColor;
    [iconView addSubview:iconImageView];
    
    // Title Label
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.13 alpha:1.0];
    [cardView addSubview:titleLabel];
    
    // Description Label
    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = description;
    descLabel.font = [UIFont systemFontOfSize:12];
    descLabel.numberOfLines = 2;
    descLabel.textColor = [UIColor colorWithRed:0.42 green:0.45 blue:0.50 alpha:1.0];
    [cardView addSubview:descLabel];
    
    // Setup Masonry constraints
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(cardView).offset(20);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(iconView);
        make.size.mas_equalTo(CGSizeMake(24, 24));
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconView.mas_bottom).offset(12);
        make.left.equalTo(cardView).offset(20);
        make.height.mas_equalTo(20);
        make.right.equalTo(cardView).offset(-20);
    }];
    
    [descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(4);
        make.left.equalTo(cardView).offset(20);
        make.right.equalTo(cardView).offset(-20);
        make.height.mas_equalTo(30);
        make.bottom.lessThanOrEqualTo(cardView).offset(-20);
    }];
    
    return cardView;
}

- (UIView *)createFileItem:(NSDictionary *)fileInfo {
    UIView *itemView = [[UIView alloc] init];
    
    // Icon View
    UIView *iconView = [[UIView alloc] init];
    iconView.layer.cornerRadius = 8;
    [itemView addSubview:iconView];
    
    NSString *colorName = fileInfo[@"color"];
    if ([colorName isEqualToString:@"red"]) {
        iconView.backgroundColor = [UIColor colorWithRed:0.99 green:0.92 blue:0.92 alpha:1.0];
    } else if ([colorName isEqualToString:@"yellow"]) {
        iconView.backgroundColor = [UIColor colorWithRed:1.0 green:0.98 blue:0.86 alpha:1.0];
    } else {
        iconView.backgroundColor = [UIColor colorWithRed:0.86 green:0.98 blue:0.90 alpha:1.0];
    }
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage systemImageNamed:@"doc.fill"];
    if ([colorName isEqualToString:@"red"]) {
        iconImageView.tintColor = [UIColor colorWithRed:0.86 green:0.20 blue:0.27 alpha:1.0];
    } else if ([colorName isEqualToString:@"yellow"]) {
        iconImageView.tintColor = [UIColor colorWithRed:0.92 green:0.68 blue:0.13 alpha:1.0];
    } else {
        iconImageView.tintColor = [UIColor colorWithRed:0.13 green:0.69 blue:0.30 alpha:1.0];
    }
    [iconView addSubview:iconImageView];
    
    // Text Container
    UIView *textContainer = [[UIView alloc] init];
    [itemView addSubview:textContainer];
    itemView.backgroundColor  = [UIColor yellowColor];
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = fileInfo[@"name"];
    nameLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    nameLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.13 alpha:1.0];
    [textContainer addSubview:nameLabel];
    
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.text = fileInfo[@"time"];
    timeLabel.font = [UIFont systemFontOfSize:12];
    timeLabel.textColor = [UIColor colorWithRed:0.42 green:0.45 blue:0.50 alpha:1.0];
    [textContainer addSubview:timeLabel];
    
    // Open Button
    UIButton *openButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [openButton setTitle:@"Open" forState:UIControlStateNormal];
    openButton.layer.cornerRadius = 5 ;
    openButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [openButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [openButton setBackgroundColor:[UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0]];
    [openButton setEnabled:YES ];
    [openButton addTarget:self action:@selector(openRecentFileButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [itemView addSubview:openButton];
    
    // Setup Masonry constraints
    [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
    }];
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(itemView);
    
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
 
    
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(iconView);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    
    [textContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(12);
        make.centerY.equalTo(itemView);
//        make.right.equalTo(openButton.mas_left).offset(-12);
    }];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(textContainer);
    }];
    
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameLabel.mas_bottom).offset(2);
        make.left.right.bottom.equalTo(textContainer);
    }];
    itemView.backgroundColor = [UIColor redColor];
    [openButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(itemView);
        make.left.equalTo(itemView).offset(200);
        make.width.equalTo(@40);
    }];
    
    return itemView;
}

- (UIButton *)createNavButton:(NSString *)iconName 
                        title:(NSString *)title 
                       active:(BOOL)active 
                          tag:(NSInteger)tag {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = tag;
    [button addTarget:self action:@selector(navButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    // Create vertical stack
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 4;
    stackView.userInteractionEnabled = NO;
    [button addSubview:stackView];
    
    // Icon
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage systemImageNamed:iconName];
    iconView.tintColor = active ? [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0] : [UIColor colorWithRed:0.61 green:0.64 blue:0.69 alpha:1.0];
    [stackView addArrangedSubview:iconView];
    
    // Title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textColor = active ? [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0] : [UIColor colorWithRed:0.61 green:0.64 blue:0.69 alpha:1.0];
    [stackView addArrangedSubview:titleLabel];
    
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(button);
    }];
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(24, 24));
    }];
    
    return button;
}

#pragma mark - Data Loading

- (void)loadCADImage {
    // 模拟加载CAD图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 这里可以添加实际的图片加载逻辑
        NSURL *imageURL = [NSURL URLWithString:@"https://images.unsplash.com/photo-1503387762-592deb58ef4e?auto=format&fit=crop&w=400&q=80"];
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
        UIImage *image = [UIImage imageWithData:imageData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.cadImageView.image = image;
        });
    });
}

- (void)loadRecentFiles {
    // 模拟加载最近文件数据
    NSLog(@"Loading recent files...");
}

#pragma mark - Button Actions

- (void)settingsButtonTapped {

    ProfileViewController *profileVC = [[ProfileViewController alloc] init];
    [self.navigationController pushViewController:profileVC animated:YES];
}

- (void)openFileButtonTapped {
    NSLog(@"Open file button tapped");
//    [self showAlert:@"打开文件" message:@"正在打开CAD查看器..."];
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

- (void)historyButtonTapped {
    NSLog(@"History button tapped");
    HistoryViewController *historyVC = [[HistoryViewController alloc] init];
    [self.navigationController pushViewController:historyVC animated:YES];
}

- (void)converterButtonTapped {
    NSLog(@"Converter button tapped");
    UnitConverterViewController *converterVC = [[UnitConverterViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:converterVC];
    navController.navigationBarHidden = YES;
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}

- (void)measurementButtonTapped {
    NSLog(@"Measurement button tapped");
    [self showAlert:@"测量工具" message:@"正在打开测量工具..."];
}

- (void)viewAllFilesButtonTapped {
    NSLog(@"View all files button tapped");
    [self showAlert:@"文件管理" message:@"正在打开文件管理..."];
}

- (void)openRecentFileButtonTapped:(UIButton *)sender {
    NSLog(@"Open recent file button tapped");
    [self showAlert:@"打开文件" message:@"正在打开选中的文件..."];
}

- (void)navButtonTapped:(UIButton *)sender {
    NSLog(@"Nav button tapped: %ld", (long)sender.tag);
    
    // Update nav button states
    for (UIButton *button in self.navButtons) {
        UIStackView *stackView = button.subviews.firstObject;
        UIImageView *iconView = stackView.arrangedSubviews.firstObject;
        UILabel *titleLabel = stackView.arrangedSubviews.lastObject;
        
        BOOL isActive = (button.tag == sender.tag);
        UIColor *color = isActive ? [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0] : [UIColor colorWithRed:0.61 green:0.64 blue:0.69 alpha:1.0];
        
        iconView.tintColor = color;
        titleLabel.textColor = color;
    }
    
    NSArray *titles = @[@"主页", @"文件", @"工具", @"设置"];
    [self showAlert:titles[sender.tag] message:[NSString stringWithFormat:@"正在打开%@...", titles[sender.tag]]];
}

#pragma mark - Helper Methods

- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title 
                                                                   message:message 
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" 
                                                       style:UIAlertActionStyleDefault 
                                                     handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - UIDocumentPickerViewController Delegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    if ([[url absoluteString] containsString:@".dwg"]) {
        if (controller.documentPickerMode == UIDocumentPickerModeImport) {
            NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
            NSString *fileName = [array lastObject];
            fileName = [fileName stringByRemovingPercentEncoding];
            NSString* realName = fileName;
            fileName = [NSString stringWithFormat:@"%@-%@",[SnToolManager getCurrentFormattedTime],fileName];
            fileName = [fileName stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
            NSError *error;
            [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
                if (error) {
                }
                NSData *data = [NSData dataWithContentsOfURL: newURL];
                NSString *path = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
                [data writeToFile:path atomically:YES];
                Snmodel* model = [[Snmodel alloc]init];
                model.timestamp = [SnToolManager getCurrentTimestamp];
                model.filePath = fileName;
                model.documentName = realName;
                [SnDataSourceTool addModelData:model];
                [SVProgressHUD dismissWithDelay:1 completion:^{
               [SnToolManager pushCADFileWithModel:model navigationController:self.navigationController];
                }];
            }];
        }
    }
    else{
        [SVProgressHUD showErrorWithStatus:@"Files of this format are not supported"];
        [SVProgressHUD dismissWithDelay:2];
    }
}
@end
